package com.example.hao.aidl_client;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.xykj.aidl.IMyAidlInterface;
import com.xykj.aidl.Student;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private IMyAidlInterface iMyAidlInterface;

    public static final String TAG = "MyService";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 点击绑定远程服务
     *
     * @param view
     */
    public void BindRemoteServices(View view) {

        Intent intent = new Intent();

        intent.setPackage("com.example.hao.aidl_service");

        intent.setAction("com.xykj.aidl.action");

        bindService(intent, this, Context.BIND_AUTO_CREATE);


    }

    /**
     * 绑定服务成功
     *
     * @param name
     * @param service
     */
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Toast.makeText(this, "绑定服务成功!", Toast.LENGTH_SHORT).show();

        if (service != null) {
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }
        Log.i(TAG, "onServiceConnected: 绑定服务成功>>>");
    }


    /**
     * 服务绑定异常断开
     *
     * @param name
     */
    @Override
    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(this, "服务绑定异常 断开连接", Toast.LENGTH_SHORT).show();
        Log.e(TAG, "onServiceDisconnected: 服务绑定异常 断开连接");
    }

    /**
     * 点击 发送数据给远程服务
     *
     * @param view
     */
    public void SendData2RemoteServices(View view) {

        try {
            iMyAidlInterface.basicTypes(119, 789L, true, 6.6F, 8.8, "abc");
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    public void SendStudent2RemoteServices(View view) {
        try {
            Student student = new Student("张三", '男', 11);
            iMyAidlInterface.setStudent(student);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void getStudentFromRemoteServices(View view) {
        try {
            Student student = new Student("张三", '男', 11);
            Log.w(TAG, "getStudentFromRemoteServices: "+student );
            iMyAidlInterface.getStudent(student);
            Log.w(TAG, "getStudentFromRemoteServices: "+student );
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
